﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_Permission_CreateEmployee : System.Web.UI.UserControl
{
    DBDataContext dtx = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SetupForm();
            //LoadTree();
        }
    }
    private void SetupForm()
    {
        dtpWorkDate.SelectedDate = DateTime.Now.Date;
        dtpWorkDate.MinDate = DateTime.Now;
        gv.Visible = false;
        this.txtSkype.Enabled = false;
        this.txtYahoo.Enabled = false;
        this.txtPhoneComp.Enabled = false;

        var q = dtx.Combo_Role("");
        cboRole.DataSource = q;
        cboRole.DataTextField = "Name";
        cboRole.DataValueField = "Code";
        cboRole.DataBind();
        cboRole.Items.Insert(0, new RadComboBoxItem("--Chọn--", ""));
        cboRole.SelectedIndex = 0;

        cboRoleSearch.DataSource = q;
        cboRoleSearch.DataTextField = "Name";
        cboRoleSearch.DataValueField = "Code";
        cboRoleSearch.DataBind();
        cboRoleSearch.Items.Insert(0, new RadComboBoxItem("--Chọn--", ""));
        cboRoleSearch.SelectedIndex = 0;

        //Load tinh thanh
        int ProvinceID = Session["ProvinceID"] == null ? 0 : int.Parse(Session["ProvinceID"].ToString());
        int isProvinceAll = (ProvinceID == 0 ? 1 : 0);
        Utils.loadLocation(cboProvinceIDsearch, 0, isProvinceAll, ProvinceID);
        Utils.loadLocation(cboProvince, 0, isProvinceAll, ProvinceID);
        //load Shop
        int ShopID = Session["ShopID"] == null ? 0 : int.Parse(Session["ShopID"].ToString());
        int isShopAll = (ShopID == 0 ? 1 : 0);
        Utils.loadShopByProvinceToCombo(cboShop, isShopAll, ProvinceID, ShopID, "");
        Utils.loadShopByProvinceToCombo(cboShopSearch, isShopAll, ProvinceID, ShopID, "");

       
       // cboCreateUser.Items.Insert(0, new RadComboBoxItem("--Chọn--", ""));
        cboCreateUser.Items.Insert(0, new RadComboBoxItem("Có", "Y"));
        cboCreateUser.Items.Insert(1, new RadComboBoxItem("Không", "N"));

       // cboIsAdvisor.Items.Insert(0, new RadComboBoxItem("--Chọn--", ""));
        cboIsAdvisor.Items.Insert(0, new RadComboBoxItem("Không", "N"));
        cboIsAdvisor.Items.Insert(1, new RadComboBoxItem("Có", "Y"));

       
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        using (var transation = new System.Transactions.TransactionScope())
        {
            try
            {
                Employee emp = createEmpObj();
                if (this.txtEmployeeCode.Text == "")
                {
                    string isCreateUser = this.cboCreateUser.SelectedValue;
                    dtx.Insert<Employee>(emp);
                    dtx.SubmitChanges();
                    if (isCreateUser.ToLower() == "y")
                    {
                        string defaultPassword = "123456";
                        string PasswordMD5 = Utils.Encrypt(defaultPassword);
                        User user = new User();
                        user.EmployeeID = emp.ID;
                        user.RoleID = emp.RoleID;
                        user.UserName = this.txtUserName.Text.Trim();
                        user.Password = PasswordMD5;
                        user.CreatedBy = Session["UserName"].ToString();
                        user.LastUpdatedBy = Session["UserName"].ToString();
                        user.CreatedDateTime = DateTime.Now;
                        user.LastUpdatedDateTime = DateTime.Now;
                        user.Status = 'P';
                        dtx.Insert<User>(user);

                        this.txtPassword.Text = defaultPassword;
                    }
                    this.txtEmployeeCode.Text = emp.EmployeeCode;
                    this.btnSave.Enabled = false;
                }
                else//edit
                {
                    dtx.Update<Employee>(emp);
                    var userE = (from u in dtx.Users where u.EmployeeID == emp.ID select u).FirstOrDefault();
                    if (userE != null)
                    {
                        string isCreateUser = this.cboCreateUser.SelectedValue;
                        if (isCreateUser.ToLower() != "y")
                        {
                            dtx.Delete<User>(userE);
                        }
                        else
                        {
                            userE.RoleID = emp.RoleID;
                            userE.CreatedBy = Session["UserName"].ToString();
                            userE.LastUpdatedBy = Session["UserName"].ToString();
                            userE.CreatedDateTime = DateTime.Now;
                            userE.LastUpdatedDateTime = DateTime.Now;
                            dtx.Update<User>(userE);
                        }
                    }
                    else
                    {
                        string isCreateUser = this.cboCreateUser.SelectedValue;
                        if (isCreateUser.ToLower() == "y")
                        {
                            string defaultPassword = "123456";
                            string PasswordMD5 = Utils.Encrypt(defaultPassword);
                            User user = new User();
                            user.EmployeeID = emp.ID;
                            user.RoleID = emp.RoleID;
                            user.UserName = this.txtUserName.Text.Trim();
                            user.Password = PasswordMD5;
                            user.CreatedBy = Session["UserName"].ToString();
                            user.LastUpdatedBy = Session["UserName"].ToString();
                            user.CreatedDateTime = DateTime.Now;
                            user.LastUpdatedDateTime = DateTime.Now;
                            user.Status = 'P';
                            dtx.Insert<User>(user);

                            this.txtPassword.Text = defaultPassword;
                        }
                    }
                }
                dtx.SubmitChanges();
                transation.Complete();
                JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công!");
            }
            catch (Exception ex)
            {
                this.btnSave.Enabled = true;
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
                ControlUtil.LogError("-----------------------------");
                ControlUtil.LogError("CreateEmployee-btnSave_Click");
                ControlUtil.LogError(ex.ToString());
                ControlUtil.LogError("-----------------------------");
            }
        }
    }

    private Employee createEmpObj()
    {
        Employee emp = new Employee();
        try
        {
            if (this.txtEmployeeCode.Text == "")
            {
                //Lay ma sau cung
                int lenZero = 3;//So ky tu khôg tính chữ cái đưungs đầu. ví dụ KH0000001 --> 7, k tính KH
                var CodeMax = dtx.Employees.Max(d => d.OrderNumber);
                int MaxOrderNumber = (CodeMax == null ? 0 : Convert.ToInt32(CodeMax)) + 1;
                String LastCode = ("000" + MaxOrderNumber).ToString();
                String Code = LastCode.Substring(LastCode.Length - lenZero);
                //End
                emp.OrderNumber = MaxOrderNumber;
                emp.EmployeeCode = Code;
            }
            else
            {
                var em = dtx.Employees.FirstOrDefault<Employee>(a => a.EmployeeCode == this.txtEmployeeCode.Text);
                if (em != null)
                {
                    emp = em;
                }
            }
            string empName = this.txtEmployeeName.Text;
            int roleID = int.Parse(this.cboRole.SelectedValue);
            int shopID = int.Parse(this.cboShop.SelectedValue);
            string address = this.txtAddress.Text;
            string IDCard = this.txtIDCard.Text;
            string phoneNumber = this.txtPhoneEmp.Text;
            DateTime? workDate = this.dtpWorkDate.SelectedDate;
            string email = this.txtEmail.Text;
            bool isAdvisor = this.cboIsAdvisor.SelectedValue.ToLower()=="n"?false:true;
            string phoneComp = this.txtPhoneComp.Text;
            string yahoo = this.txtYahoo.Text.Trim();
            string skype = this.txtSkype.Text.Trim();
            int provinceID =int.Parse( this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);
            emp.EmplyeeName = empName;
            emp.RoleID = roleID;
            emp.ShopID = shopID;
            emp.Address = address;
            emp.IDCard = IDCard;
            emp.IsAdvisor = isAdvisor;
            emp.PhoneNumberEmp = phoneNumber;
            emp.DateOfWork = workDate;
            emp.Email = email;
            emp.PhoneNumberComp = phoneComp;
            emp.Skype = skype;
            emp.Yahoo = yahoo;
            emp.ProvinceID = provinceID;
            emp.CreatedBy = Session["UserName"].ToString();
            emp.LastUpdatedBy = Session["UserName"].ToString();
            emp.CreatedDateTime = DateTime.Now;
            emp.LastUpdatedDateTime = DateTime.Now;
            emp.Status = 'A';

        }
        catch (Exception ex)
        {
            this.btnSave.Enabled = true;
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("CreateEmployee-createEmpObj");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
        return emp;
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/CreateEmployee", false);
    }

    protected void cboCreateUser_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (this.cboCreateUser.SelectedValue.ToLower() == "n")
        {
            this.RequiredFieldValidator2.Enabled = false;
            this.txtUserName.Enabled = false;
        }
        else
        {
            this.RequiredFieldValidator2.Enabled = true;
            this.txtUserName.Enabled = true;
        }
    }

    protected void cboIsAdvisor_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        if (this.cboIsAdvisor.SelectedValue.ToLower() == "n")
        {
            this.txtSkype.Enabled = false;
            this.txtYahoo.Enabled = false;
            this.txtPhoneComp.Enabled = false;
        }
        else
        {
            this.txtSkype.Enabled = true;
            this.txtYahoo.Enabled = true;
            this.txtPhoneComp.Enabled = true;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        LoadData();
        gv.DataBind();
    }

    protected void gv_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        if (RadMultiPag1.SelectedIndex == 2)//Tab tim kiem
        {
            LoadData();
        }
    }
    protected void gv_ItemCommand(object sender, GridCommandEventArgs e)
    {
        string commandName = e.CommandName;
        string EmpID = e.CommandArgument.ToString();
        if (commandName == "EditDelItem")
        {
            var user = dtx.Users.FirstOrDefault<User>(b => b.EmployeeID == int.Parse(EmpID));
            var emp = dtx.Employees.FirstOrDefault<Employee>(a => a.ID == int.Parse(EmpID));
            dtx.Delete<User>(user);
            dtx.Delete<Employee>(emp);
            dtx.SubmitChanges();
            LoadData();
            gv.DataBind();
        }
        else
        {
            RadPageView1.Selected = true;
            TabStrip1.SelectedIndex = 0;
            this.btnSave.Enabled = true;

            this.txtUserName.Enabled = false;
            var user = dtx.Users.FirstOrDefault<User>(b => b.EmployeeID == int.Parse(EmpID));
            var emp = dtx.Employees.FirstOrDefault<Employee>(a => a.ID == int.Parse(EmpID));

            this.txtEmployeeName.Text = emp.EmplyeeName;

            this.cboRole.SelectedValue = emp.RoleID.ToString();
            this.cboShop.SelectedValue = emp.ShopID.ToString();
            this.txtAddress.Text = emp.Address;
            this.txtIDCard.Text= emp.IDCard;
            this.txtPhoneEmp.Text = emp.PhoneNumberEmp;
            this.dtpWorkDate.MinDate = DateTime.Now.AddYears(-30);
            this.dtpWorkDate.SelectedDate = emp.DateOfWork;
            this.txtEmail.Text = emp.Email;
            this.cboIsAdvisor.SelectedValue = emp.IsAdvisor== false?"N" : "Y";
            this.txtPhoneComp.Text = emp.PhoneNumberComp;
            this.txtYahoo.Text = emp.Yahoo;
            this.txtSkype.Text = emp.Skype;
            this.txtEmployeeCode.Text = emp.EmployeeCode;
            if (user != null)
            {
                this.cboCreateUser.SelectedValue = "Y";
                //this.cboCreateUser.Enabled = false;
                //this.txtPassword.Text = user.Password;
                this.txtUserName.Text = user.UserName;
            }
            
        }
    }
    private void LoadData()
    {
         gv.Visible = true;
        string empCode = this.txtEmployeeCodeSearch.Text;
        string empName = this.txtEmployeeNameSearch.Text;
        int roleID = int.Parse(this.cboRoleSearch.SelectedValue == "" ? "0" : this.cboRoleSearch.SelectedValue);
        int shopID = int.Parse(this.cboShopSearch.SelectedValue == "" ? "0" : this.cboShopSearch.SelectedValue);
        int provinceID = int.Parse(this.cboProvinceIDsearch.SelectedValue == "" ? "0" : this.cboProvinceIDsearch.SelectedValue);
        string UserName = this.txtUserNameSearch.Text;
        string phoneNumber = this.txtPhoneEmpSearch.Text;

        int PageNumber = gv.CurrentPageIndex + 1;
        int PageSize = gv.PageSize;

        var q = dtx.Employee_Search(empCode,empName,roleID,provinceID,shopID,UserName,phoneNumber,PageSize, PageNumber).ToList();
        if (q.Count > 0)
        {
            gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            gv.VirtualItemCount = q[0].TotalRows.Value;
            gv.DataSource = q;
            if (q.Count > 5)
            {
                //gv.Height = 120;
                gv.ClientSettings.Scrolling.AllowScroll = true;

                gv.ClientSettings.Scrolling.UseStaticHeaders = true;
            }
        }
        else
        {
            gv.DataSource = new DataTable();
        }
    }


    protected void cboProvince_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        int ProvinceID = int.Parse(this.cboProvince.SelectedValue == "" ? "0" : this.cboProvince.SelectedValue);
        Utils.loadShopByProvinceToCombo(cboShop, 1, ProvinceID,0, "");
    }

    protected void cboRole_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        string roleID = this.cboRole.SelectedValue;
        this.cboProvince.Enabled = true;
        this.cboShop.Enabled = true;
        if (roleID == "1" || roleID =="5")//admin hoac nhan vien tong dai
        {
            this.cboProvince.SelectedIndex = 0;
            this.cboShop.SelectedIndex = 0;
            this.cboProvince.Enabled = false;
            this.cboShop.Enabled = false;

        }
        else if (roleID == "4")//quan ly vung
        {
            this.cboShop.SelectedIndex = 0;
            this.cboShop.Enabled = false;
        }

        this.ShopRequired.Enabled = this.cboShop.Enabled;
        this.cboProvinceRequired.Enabled = this.cboProvince.Enabled;
    }

    protected void cboProvinceIDSearch_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        int ProvinceID = int.Parse(this.cboProvinceIDsearch.SelectedValue == "" ? "0" : this.cboProvinceIDsearch.SelectedValue);
        Utils.loadShopByProvinceToCombo(cboShopSearch, 1, ProvinceID,0, "");
    }
}